<template>
  <div class="login-wrap">
    <el-form
      :model="loginForm"
      :rules="rules"
      :label-position="labelPosition"
      ref="myForm"
      label-width="80px"
      class="login-from"
    >
      <h1>用户登录</h1>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <!-- 在文本框前面加字体图标 -->
        <el-input
          prefix-icon="iconfont icon-showpassword"
          type="password"
          v-model="loginForm.password"
        ></el-input>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button @click="submitForm" class="login-btn" type="primary">登录</el-button>
        <!-- <el-button @click="resetForm">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 导入api
import { loginApi } from '@/api/login'

export default {
  name: 'LoginVue',
  data() {
    return {
      // 表单文字描述的位置
      labelPosition: 'top',
      // 表单数据
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 定义表单验证规则
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 3, max: 10, message: '密码长度在3-10位', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      // 表单提交验证
      this.$refs.myForm.validate(async valid => {
        if (valid) {
          // 验证通过
          // 发起ajax请求，实现登录效果
          const res = await loginApi(this.loginForm)
          // 从里面获取登录成功的token，并保存起来,建议保存在本地缓存的 sessionStorage：窗口关闭就失效
          window.sessionStorage.setItem('token', res.token)
          this.$message.success('登录成功')
          this.$router.push('/home')
          /* console.log(res);
          const { meta, data } = res.data;
          if (meta.status == 200) {
            this.$message.success("登录成功");
            //this.$router.push({path:'/home'})  //path跳转
            this.$router.push("Home"); //name跳转
          } else {
            this.$message.error(meta.msg);
          } */
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.myForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-wrap {
  background-color: #324152;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  h1 {
    font-size: 24px;
  }
  // 登录表单
  .login-from {
    background-color: #fff;
    width: 500px;
    padding: 30px;
    border-radius: 5px;
    // 提交按钮
    .login-btn {
      width: 100%;
    }
  }
}
</style>
